#!/usr/bin/env python3
"""
为文件表添加描述和标签字段的数据库迁移脚本
"""

import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from sqlalchemy import create_engine, text
from app.core.config import settings

def migrate_database():
    """执行数据库迁移"""
    engine = create_engine(settings.DATABASE_URL)
    
    print("开始为文件表添加描述和标签字段...")
    
    try:
        with engine.connect() as conn:
            # 添加描述字段
            try:
                conn.execute(text("""
                    ALTER TABLE files 
                    ADD COLUMN description TEXT DEFAULT ''
                """))
                print("✓ 成功添加 description 字段")
            except Exception as e:
                if "Duplicate column name" in str(e) or "already exists" in str(e):
                    print("- description 字段已存在，跳过")
                else:
                    print(f"✗ 添加 description 字段失败: {e}")
            
            # 添加标签字段
            try:
                conn.execute(text("""
                    ALTER TABLE files 
                    ADD COLUMN tags TEXT DEFAULT ''
                """))
                print("✓ 成功添加 tags 字段")
            except Exception as e:
                if "Duplicate column name" in str(e) or "already exists" in str(e):
                    print("- tags 字段已存在，跳过")
                else:
                    print(f"✗ 添加 tags 字段失败: {e}")
            
            # 提交更改
            conn.commit()
            print("✓ 数据库迁移完成")
            
    except Exception as e:
        print(f"✗ 数据库迁移失败: {e}")
        return False
    
    return True

if __name__ == "__main__":
    success = migrate_database()
    if success:
        print("\n=== 迁移成功 ===")
        print("现在可以为文件添加描述和标签信息了")
    else:
        print("\n=== 迁移失败 ===")
        print("请检查数据库连接和权限")
        sys.exit(1)